package org.meeting.radish.util;

import org.meeting.radish.entity.TestCase;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class TestCaseUtil {

    public static Map<String, TestCase> getTestCasesFromFiles(MultipartFile[] files, Integer qid) throws IOException {
        Map<String, TestCase> testCases = new HashMap<>();
        for (MultipartFile file : files) {
            String originalFilename = file.getOriginalFilename();

            if (originalFilename == null) {
                continue;
            }

            String[] split = originalFilename.split("\\.");
            if (split.length != 2) {
                continue;
            }

            BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()));

            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            TestCase aCase;
            switch (split[1]) {
                case "in":
                    if (!testCases.containsKey(split[0])) {
                        aCase = new TestCase();
                        aCase.setIn(sb.toString());
                        aCase.setQid(qid);
                        testCases.put(split[0], aCase);
                    } else {
                        testCases.get(split[0]).setIn(sb.toString());
                    }

                    break;
                case "out":

                    if (!testCases.containsKey(split[0])) {
                        aCase = new TestCase();
                        aCase.setOut(sb.toString());
                        aCase.setQid(qid);
                        testCases.put(split[0], aCase);
                    } else {
                        testCases.get(split[0]).setOut(sb.toString());
                    }

                    break;
            }


        }

        return testCases;
    }

}
